
/**
 * 获得 B 站用户头像 URL
 * @param {number} uid 
 */
function fetchAvatarUrl(uid) {
  return `/aurora/asset/danmaku/avatar?uId=${uid}`;
}

/** @type {Item[]} */
let promiseList = [];
/** @type {Item} */
let currentItem = null;

class Item {
  constructor(uid, resolve, reject) {
    this.uid = uid;
    this.resolve = resolve;
    this.reject = reject;
    this.canceled = false;
  }
}

function waitForFetchingAvatar(uid) {
  let resolve = null;
  let reject = null;
  let promise = new Promise((rs, rj) => {
    resolve = rs;
    reject = rj;
  });

  let item = new Item(uid, resolve, reject);
  if (currentItem != null) {
    promiseList.push(item);
    console.log('等待: ' + uid);
    return {
      promise,
      cancel : () => {
        item.canceled = true;
        reject('waitForFetchingAvatar has been canceled');
      }
    };
  }
  
  currentItem = item;
  fetchAvatar();
  return {
    promise,
    cancel : () => { }
  };
}

function fetchAvatar() {
  while (currentItem == null) {
    currentItem = promiseList.pop();
    if (currentItem && currentItem.canceled) {
      currentItem = null;
    } else if (currentItem == null) {
      return;
    }
  }

  let img = document.createElement('img');
  img.onload = () => {
    currentItem.resolve(img);
    currentItem = null;
    fetchAvatar();
  }
  img.onerror = (e) => {
    currentItem.reject(e);
    currentItem = null;
    fetchAvatar();
  }
  img.src = fetchAvatarUrl(currentItem.uid);
}

export {
  fetchAvatarUrl, waitForFetchingAvatar
};
